/*
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-11-18 15:33:04
 * @LastEditors: zhangxiang
 * @LastEditTime: 2022-11-22 15:26:35
 * @Description:
 *
 */

import { asyncRoutes, constantRoutes } from '@/router'

/**
 * @description: 使用 pagePermissions 判断相应路由是否有权限
 * @param {*} pagePermissions
 * @param {*} route
 * @return {*}
 */
function hasPermission(pagePermissions, route) {
  if (route.meta && route.meta.menuKey) {
    return Object.prototype.hasOwnProperty.call(pagePermissions, route.meta.menuKey) // 页面权限数组是否包含路由的menuKey
  } else {
    return false
  }
}

/**
 * @description: 遍历过滤动态路由，某个路由有权限，则其子路由父路由都有权限
 * @param {*} routes
 * @param {*} pagePermissions
 * @return {*}
 */
export function filterAsyncRoutes(routes, pagePermissions) {
  const res = []

  routes.forEach((route) => {
    const tmp = { ...route }
    if (tmp.alwaysAdd) {
      // 总是添加
      res.push(tmp)
    } else {
      if (hasPermission(pagePermissions, tmp)) {
        // 有权限
        // 添加路由
        res.push(tmp)
      } else {
        // 无权限
        // 判断 children
        if (tmp.children) {
          // 存在子路由
          // 遍历出子路由有权限的
          tmp.children = filterAsyncRoutes(tmp.children, pagePermissions) // 递归遍历
        }
        // 存在有权限的子路由
        if (tmp.children && tmp.children.length > 0) {
          // 添加
          res.push(tmp)
        }
      }
    }
  })

  return res
}

const state = {
  routes: [], // 路由
  addRoutes: [] // 添加的路由
}

const mutations = {
  /**
   * @description: 设置路由
   * @return {*}
   */
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  /**
   * @description: 生成路由
   * @param {*} commit
   * @param {*} pagePermissions
   * @return {*}
   */
  generateRoutes({ commit }, pagePermissions) {
    return new Promise((resolve) => {
      // 过滤动态路由
      const accessedRoutes = filterAsyncRoutes(
        asyncRoutes,
        pagePermissions
      )
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
